class_name Traits
extends Control

# ===============================================

@export var arena_grid: UnitGrid

# ===============================================

@onready var traits_container: VBoxContainer = $TraitsContainer
@onready var scene_spawner: SceneSpawner = $SceneSpawner

# ===============================================

var current_traits: Dictionary = {}
var traits_to_update: Array
var active_traits: Array[Trait]

# ===============================================

func __create_trait_ui(trait_data: Trait, units: Array[Unit]) -> void:
	var trait_ui: TraitUI = scene_spawner.spawn_scene(traits_container) as TraitUI
	trait_ui.trait_data = trait_data
	trait_ui.update(units)
	current_traits[trait_data] = trait_ui
	if trait_ui.active:
		active_traits.append(trait_data)


func __update_trait_ui(trait_data: Trait, units: Array[Unit]) -> void:
	var trait_ui: TraitUI = current_traits[trait_data] as TraitUI
	trait_ui.update(units)
	traits_to_update.erase(trait_data)
	if trait_ui.active:
		active_traits.append(trait_data)


func __move_active_traits_to_top() -> void:
	for i: int in active_traits.size():
		var trait_ui: TraitUI = current_traits[active_traits[i]] as TraitUI
		traits_container.move_child(trait_ui, i)


func __remove_orphan_traits() -> void:
	for trait_data: Trait in traits_to_update:
		var trait_ui: TraitUI = current_traits[trait_data] as TraitUI
		current_traits.erase(trait_data)
		trait_ui.queue_free()


# ===============================================

func _ready() -> void:
	arena_grid.unit_grid_changed.connect(
		func():
			traits_to_update = current_traits.keys()
			active_traits.clear()
			var units := arena_grid.get_all_units()
			var traits := Trait.get_unique_traits_for_units(units)
			for traits_data: Trait in traits:
				if current_traits.has(traits_data):
					__update_trait_ui(traits_data, units)
				else:
					__create_trait_ui(traits_data, units)
			__move_active_traits_to_top()
			__remove_orphan_traits()
	)
	for ui:TraitUI in traits_container.get_children():
		ui.queue_free()
